<?php
namespace app\massage\model;

use app\BaseModel;
use think\facade\Db;

class Order extends BaseModel
{
    //定义表名
    protected $name = 'shequshop_car_order';


     protected $append = [


         'order_goods',

         'all_goods_num',

         'game_info',

         'hx_user_name'

     ];


    /**
     * @param $value
     * @param $data
     * @功能说明:获取订单二维码
     * @author chenniang
     * @DataTime: 2021-10-08 14:07
     */
     public function getQrAttr($value,$data){

         if(isset($value)&&!empty($data['uniacid'])&&!empty($data['id'])){

             if(empty($value)){

                 $user_model = new User();

                 $input = [

                     'id'   => $data['id'],

                     'page' => 'mine/pages/order/hexiao'

                 ];
                 //获取二维码
                 $value = $user_model->orderQr($input,$data['uniacid']);

                 $this->dataUpdate(['id'=>$input['id']],['qr'=>$value]);

             }

             return $value;
         }

     }

    /**
     * @author chenniang
     * @DataTime: 2021-09-28 14:12
     * @功能说明:核销人姓名
     */
     public function getHxUserNameAttr($value,$data){

         if(!empty($data['hx_user'])){

             $user_model = new User();

             $name = $user_model->where(['id'=>$data['hx_user']])->value('nickName');

             return $name;
         }

     }


    /**
     * @author chenniang
     * @DataTime: 2021-09-27 16:21
     * @功能说明:赛事信息
     */
     public function getGameInfoAttr($value,$data){

         if(!empty($data['id'])){

             $game_model = new CarGame();

             $dis = [

                 'type' => 2,

                 'record_id' => $data['id']
             ];

             $list = $game_model->dataInfo($dis);

             return $list;

         }

     }




    /**
     * @param $value
     * @param $data
     * @功能说明:总商品数量
     * @author chenniang
     * @DataTime: 2021-03-25 14:39
     */
     public function getAllGoodsNumAttr($value,$data){

         if(!empty($data['id'])){

             $order_goods_model = new OrderGoods();

             $dis = [

                 'order_id' => $data['id']
             ];

             $num = $order_goods_model->where($dis)->sum('num');

             return $num;
         }


     }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:05
     * @功能说明:子订单信息
     */

     public function getOrderGoodsAttr($value,$data){

         if(!empty($data['id'])){

             $order_goods_model = new OrderGoods();

             $dis = [

                 'order_id' => $data['id']
             ];

             $list = $order_goods_model->where($dis)->select()->toArray();

             return $list;

         }

     }






    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:23
     * @功能说明:前端订单列表
     */

     public function indexDataList($dis,$mapor,$page=10){

         $data = $this->alias('a')
             ->join('shequshop_car_order_goods b','a.id = b.order_id')
             ->where($dis)
             ->where(function ($query) use ($mapor){
                 $query->whereOr($mapor);
             })
             ->field('a.*')
             ->group('a.id')
             ->order('a.id desc')
             ->paginate($page)
             ->toArray();

         if(!empty($data['data'])){

             foreach ($data['data'] as &$v){

                 $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

             }
         }

         return $data;

     }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataList($dis,$page=10){

        $data = $this->alias('a')
                ->join('shequshop_car_order_goods b','a.id = b.order_id')
                ->where($dis)
                ->field('a.*')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();

        if(!empty($data['data'])){

            $user_model = new User();

            foreach ($data['data'] as &$v){

                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');

            }
        }

        return $data;

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataSelect($dis,$page=10){

        $data = $this->alias('a')
            ->join('shequshop_car_order_goods b','a.id = b.order_id')
            ->where($dis)
            ->field('a.*,b.goods_id,b.goods_name,b.goods_price,b.num')
            ->group('a.id,b.goods_id')
            ->order('a.id desc')
            ->select()
            ->toArray();

        if(!empty($data)){

            $user_model = new User();

            foreach ($data as &$v){

                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');

            }
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 14:33
     * @功能说明:
     */
    public function datePrice($date,$uniacid,$cap_id=0,$end_time = '',$type=1){

        $end_time = !empty($end_time)?$end_time:$date+86399;

        $dis = [];

        $dis[] = ['transaction_id','<>',''];

        $dis[] = ['auto_refund','=',0];

        $dis[] = ['create_time','between',"$date,$end_time"];

        $dis[] = ['uniacid',"=",$uniacid];

        if(!empty($cap_id)){

            $dis[] = ['cap_id','=',$cap_id];
        }

        if($type==1){

            $price = $this->where($dis)->sum('pay_price');

            return round($price,2);

        }else{

            $count = $this->where($dis)->count();

            return $count;

        }


    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-19 09:28
     * @功能说明:计算用户下单时候的各类金额
     */
    public function payOrderInfo($user_id,$coupon=0){

        $car_model = new Car();

        $coupon_model = new Coupon();
        //获取购物车里面的信息
        $car_list  = $car_model->carPriceAndCount($user_id);

        $car_list  = $coupon_model->orderCouponData($car_list,$coupon);

        $goods_price = $car_list['car_price'];

        $data['coupon_id']   = $car_list['coupon_id'];
        //购物车列表
        $data['order_goods'] = $car_list['list'];
        //优惠券优惠
        $data['discount']    = $car_list['total_discount'];
        //总圈速
        $data['total_circle']    = $car_list['total_circle'];
        //商品总价格
        $data['init_goods_price'] = round($goods_price,2);

        $data['goods_price'] = round($goods_price-$data['discount'],2);
        //订单支付价
        $data['pay_price']   = round($data['goods_price'] ,2);

        $data['car_count']   = $car_list['car_count'];

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-09 17:43
     * @功能说明:计算车费
     */
    public function getCarPrice($coach_id,$lat,$lng,$car_type=1){

        if($car_type==0){

            return 0;
        }

        $coach_model = new Coach();

        $coach = $coach_model->dataInfo(['id'=>$coach_id]);

        $config_model = new CarPrice();

        $config = $config_model->dataInfo(['uniacid'=>$coach['uniacid']]);
        //起步距离
        $start = $config['start_distance'];
        //起步价
        $start_price = $config['start_price'];
        //每公里多少钱
        $to_price = $config['distance_price'];

        $distance = getDistances($coach['lng'],$coach['lat'],$lng,$lat);

        $distance = $distance/1000;
        //多少公里内免费
        if($distance<$config['distance_free']){

            return 0;
        }
        //超过起步距离
        if($distance>$start){

            $to_price = round($distance - $start,2)*$to_price;

            $total    = $to_price+$start_price;

            return round($total*2,2);

        }else{

            return round($start_price*2,2);
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 11:31
     * @功能说明:订单支付回调
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->dataInfo(['order_code'=>$order_code]);

        if(!empty($order)&&$order['pay_type']==1){

            Db::startTrans();

            $update = [

                'transaction_id' => $transaction_id,

                'pay_type'       => 2,

                'pay_time'       => time(),

            ];

            $res = $this->dataUpdate(['id'=>$order['id']],$update);

            if($res==0){

                Db::rollback();

                return false;

            }
            //扣除余额
            if($order['balance']>0){

                $user_model  = new User();

                $water_model = new BalanceWater();

                $user = $user_model->dataInfo(['id'=>$order['user_id']]);
                //修改用户余额
                $res = $user_model->dataUpdate(['id'=>$order['user_id']],['balance'=>$user['balance']-$order['pay_price']]);

                if($res==0){

                    Db::rollback();

                    return false;

                }
                //添加余额流水
                $insert = [

                    'uniacid' => $order['uniacid'],

                    'user_id' => $order['user_id'],

                    'price'   => $order['pay_price'],

                    'order_id'=> $order['id'],

                    'add'     => 0,

                    'type'    => 2,

                    'before_balance' => $user['balance'],

                    'after_balance'  => $user['balance']-$order['pay_price'],
                ];

                $res = $water_model->dataAdd($insert);

                if($res==0){

                    Db::rollback();

                    return false;

                }
            }

            //分销
//            $comm_model = new Commission();
//
//            $comm_model->commissionAdd($order);

            Db::commit();

//            $notice_model = new NoticeList();
//            //增加后台提醒
//            $notice_model->dataAdd($order['uniacid'],$order['id']);
            //打印
            $print_model = new Printer();

            $print_model->printer($order['id'],1,1);

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:31
     * @功能说明:团长冻结资金
     */
    public function capFrozenPrice($cap_id,$total=0,$toDay=0){

        $dis[] = ['cap_id','=',$cap_id];

        if($total==0){

            $dis[] = ['have_tx','=',0];
        }

        $dis[] = ['pay_type','>',1];

        if($toDay==1){
            //当日
            $price = $this->where($dis)->whereDay('create_time')->sum('cap_price');

        }else{

            $price = $this->where($dis)->sum('cap_price');

        }

        return round($price,2);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:31
     * @功能说明:团长冻结资金
     */
    public function capFrozenCount($cap_id,$total=0,$toDay=0){

        $dis[] = ['cap_id','=',$cap_id];

        if($total==0){

            $dis[] = ['have_tx','=',0];
        }

        $dis[] = ['pay_type','>',1];

        if($toDay==1){
            //当日
            $price = $this->where($dis)->whereDay('create_time')->count();

        }else{

            $price = $this->where($dis)->count();

        }

        return $price;

    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:41
     * @功能说明:团长佣金到账
     */
    public function capArrPrice($uniacid,$cap_id=0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',7];

        if(!empty($cap_id)){

            $dis[] = ['cap_id','=',$cap_id];
        }

        $dis[] = ['have_tx','=',0];

//        $dis[] = ['hx_time','<',time()-86400];
        $dis[] = ['hx_time','<',time()-60];

        $order = $this->where($dis)->field('id,cap_price,cap_id')->select()->toArray();

        if(!empty($order)){

            $cap_model = new Cap();

            $refund_model = new RefundOrder();

            foreach ($order as $value){
                //判断有无申请中的退款订单
                $refund_order = $refund_model->dataInfo(['order_id'=>$value['id'],'status'=>1]);

                if(empty($refund_order)){
                    //修改订单状态
                    $res = $this->where(['id'=>$value['id'],'have_tx'=>0])->update(['have_tx'=>1]);
                    //增加团长佣金
                    if($res==1){

                        $cap_cash = $value['cap_price'];

                        $cap_model->where(['id'=>$cap_id])->update(['cap_cash'=>Db::raw("cap_cash+$cap_cash")]);

                    }

                }

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 15:15
     * @功能说明:核销订单
     */
    public function hxOrder($order,$cap_id=0){

        $config_model = new Config();

        $config = $config_model->dataInfo(['uniacid'=>$order['uniacid']]);

        $update = [

            'hx_time'        => time(),

            'pay_type'       => 7,

            'hx_user'        => $cap_id,
            //可申请退款的时间
            'can_refund_time'=> time()+$config['can_tx_time']*3600

        ];

        $res = $this->dataUpdate(['id'=>$order['id']],$update);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',1];

        $dis[] = ['over_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $order = $this->where($dis)->select()->toArray();

        if(!empty($order)){

            foreach ($order as $value){

                $this->cancelOrder($value);

            }

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:退款
     */
    public function cancelOrder($order){

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$order['id'],'pay_type'=>1],['pay_type'=>-1]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];
        }

//        $goods_model = new Service();
//        //退换库存
//        foreach ($order['order_goods'] as $v){
//
//            $res =  $goods_model->setOrDelStock($v['goods_id'],$v['num'],1);
//
//            if(!empty($res['code'])){
//
//                Db::rollback();
//
//                return $res;
//
//            }
//
//        }
        //退换优惠券
        $coupon_model = new CouponRecord();

        $coupon_model->couponRefund($order['id']);

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-10 18:04
     * @功能说明:检查技师时间
     */
    public function checkTime($order,$start_time){

        $service_model = new Service();

        $coach_model   = new Coach();

        $order_model   = new Order();

        $total_long = 0;

        foreach ($order['order_goods'] as $v){

            $time_long = $service_model->where(['id'=>$v['service_id']])->value('time_long');

            $total_long+=$time_long*$v['num'];

        }

        $end_time = $start_time+$total_long*60;

        $coach = $coach_model->dataInfo(['id'=>$order['coach_id']]);

        $all_day = 1;
        //判断不是全体24小时上班
        if($coach['start_time']!='00:00'||$coach['end_time']!='24:00'){

            $all_day = 0;

        }
        //判断是否隔夜
        $s_day = date('Y-m-d',$start_time);

        $e_day = date('Y-m-d',$end_time);
        //全天不判断
        if($all_day==0){
            //说明是隔天
            if($s_day!=$e_day){

                return ['code'=>500,'msg'=>'不在技师服务时间内,技师服务时间:'.$coach['start_time'].'-'.$coach['end_time']];

            }
            //教练上班时间
            $coach_start_time = strtotime($coach['start_time'])-strtotime(date('Y-m-d',time()))+strtotime(date('Y-m-d',$start_time));
            //教练下班时间
            $coach_end_time   = strtotime($coach['end_time'])-strtotime(date('Y-m-d',time()))+strtotime(date('Y-m-d',$start_time));

            if($start_time<$coach_start_time||$end_time>$coach_end_time){

                 return ['code'=>500,'msg'=>'不在技师服务时间内,技师服务时间:'.$coach['start_time'].'-'.$coach['end_time']];

            }

        }
        //检查该时间段是否被预约
        $where[] = ['coach_id','=',$order['coach_id']];

        $where[] = ['pay_type','not in',[-1]];

        $where[] = ['end_time','>',time()];

        $order_list = $order_model->where($where)->field('id,start_time,end_time')->select()->toArray();

        if(!empty($order_list)){

            foreach ($order_list as $value){
                //判断两个时间段是否有交集
                $res = is_time_cross($start_time,$end_time,$value['start_time'],$value['end_time']);

                if($res==false){

                    return ['code'=>500,'msg'=>'该技师该时间段已经被预约:'.date('Y-m-d H:i',$value['start_time']).'-'.date('Y-m-d H:i',$value['end_time'])];

                }

            }

        }

        $arr = [

            'end_time' => $end_time,

            'time_long'=> $total_long
        ];

        return $arr;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-11 22:39
     * @功能说明:技师修改订单信息
     */
    public function coachOrdertext($input){

        $update['pay_type'] = $input['type'];

        switch ($input['type']){

            case 3:

                $update['receiving_time'] = time();

                break;
            case 4:

                $update['serout_time'] = time();

                break;
            case 5:

                $update['arrive_time'] = time();

                $update['arrive_img'] = $input['arrive_img'];

                $update['arr_lng']    = !empty($input['arr_lng'])?$input['arr_lng']:0;

                $update['arr_lat']    = !empty($input['arr_lat'])?$input['arr_lat']:0;

                $update['arr_address']= !empty($input['arr_address'])?$input['arr_address']:'';


                break;
            case 6:

                $update['start_service_time'] = time();

                break;

            case 7:

                $update['order_end_time'] = time();

                $update['end_lng']    = !empty($input['end_lng'])?$input['end_lng']:0;

                $update['end_lat']    = !empty($input['end_lat'])?$input['end_lat']:0;

                $update['end_address']= !empty($input['end_address'])?$input['end_address']:'';

                $update['end_img']    = !empty($input['end_img'])?$input['end_img']:'';

                break;
            case -1:

                $update['coach_refund_time'] = time();

                break;

        }

        return $update;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-11 23:18
     * @功能说明:技师佣金到账
     */
    public function coachBalanceArr($uniacid){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',7];

        $dis[] = ['have_tx','=',0];

//        $dis[] = ['can_tx_date','<',time()];

        $order = $this->where($dis)->field('id,coach_id,service_price,car_price,true_service_price,true_car_price')->select()->toArray();

        if(!empty($order)){

            $refund_model = new RefundOrder();

            $coach_model = new Coach();

            $comm_model  = new Commission();

            foreach ($order as $value){

                $refund_order = $refund_model->dataInfo(['order_id'=>$value['id'],'status'=>1]);

                if(empty($refund_order)){

                    Db::startTrans();
                    //分销佣金
                    $comm_model->successCash($value['id']);
                    //修改订单状态
                    $res = $this->where(['id'=>$value['id'],'have_tx'=>0])->update(['have_tx'=>1]);
                    //增加团长佣金
                    if($res!=0){

                        $cap_cash = $value['true_service_price'];

                        $car_cash = $value['true_car_price'];

                        $res = $coach_model->where(['id'=>$value['coach_id']])->update(['service_price'=>Db::raw("service_price+$cap_cash"),'car_price'=>Db::raw("car_price+$car_cash")]);

                        if($res==0){

                            Db::rollback();

                        }

                    }else{

                        Db::rollback();
                    }

                    Db::commit();

                }

            }

        }

        return true;
    }



}